package user

import (
	"github.com/astaxie/beego"

	"yikexing.com.cn/wyws/bus"
	"yikexing.com.cn/wyws/models"
	"yikexing.com.cn/wyws/services/cache"

	"encoding/json"
	"net/http"
	"io/ioutil"
	"errors"
	"time"
	"fmt"
)
const (
	MashWebServiceRestUrl= "mashWebServiceRestUrl"
)

func init() {
	bus.AddHandler("user", GetUserInfo)
	bus.AddHandler("user", GetCurrentUserInfoFromRemote)
}

var (
	usersInfoMap map[string]map[string]interface{}
)

func init() {
	usersInfoMap = make(map[string]map[string]interface{})
	initUser := make(map[string]interface{})
	initUser["id"] = "thtf001"
	initUser["name"] = "thtf-user"
	initUser["role"] = "ROLE_ADMIN"
	usersInfoMap["12345678"] = initUser
}

//根据给定的session,获取用户相关内容.
//这些内容应该包括. id, name ... 最终以map的形式输出
//这个需要对接mash当前平台. 先写死.
//参考这个 https://tower.im/projects/7c35223f18974271a093082f00daa95a/docs/35da4bf999594306b991b87b7da734e6/ 文档
func GetUserInfo(userSessionInfo *models.UserSessionInfo)  error {
	// //需要先从,本地缓存找,远端缓存找,最后是服务器找.
	// if cache.Get(userSessionInfo.SessionId) != nil || 
	// 	GetCurrentUserInfoFromRemote(&models.GetCurrentUserCommand{SessionId: userSessionInfo.SessionId}) == nil {
	// 	return nil
	// }
	// return errors.New("没有发现要查找的用户!")
	return nil
}

func GetCurrentUserInfoFromRemote(cmd *models.GetCurrentUserCommand) error {
	client := &http.Client{}
	url := fmt.Sprintf("%s?method.name=mash5.user.queryUserInfo&user.sessionId=%s", beego.AppConfig.String(MashWebServiceRestUrl), cmd.SessionId)
	reqest, err := http.NewRequest("GET", url, nil)
	if err != nil {
		beego.Debug(fmt.Sprintf("获取当前用户请求失败:%s", err))
        return errors.New(fmt.Sprintf("获取当前用户请求失败:%s", err))
	}
	response, _ := client.Do(reqest)
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	userRecivedInfo := models.UserRecivedInfo{}
	json.Unmarshal(body, &userRecivedInfo)
	if userRecivedInfo.HasSession {
		beego.Debug("在远端服务器中找到当前用户")
		err = cache.Put(cmd.SessionId, body, 24*60*60*time.Second)
		if err != nil {
			beego.Debug(fmt.Sprintf("存储用户信息到redis失败:%s", err))
        return errors.New(fmt.Sprintf("存储用户信息到redis失败:%s", err))
		}
	} else {
		beego.Debug(fmt.Sprintf("没有发现要查找的用户:%s", err))
        return errors.New(fmt.Sprintf("没有发现要查找的用户:%s", err))
	}
	return nil
}
